//
//  FindViewController.m
//  NewChat
//
//  Created by 马欢 on 16/2/27.
//  Copyright © 2016年 蓝鸥. All rights reserved.
//

#import "FindViewController.h"
#import "UIView+SDAutoLayout.h"
#import "FindTableViewCell.h"
#import "ReplyViewController.h"
#import "FindModel.h"
#import "MHDataHelper.h"
#import "SKXRongCloudManager.h"
#import "PlayerManager.h"
#define Manager [PlayerManager defaultManager]
#define HELPER [MHDataHelper shareDataHelper]
#define PLAY [SKXRongCloudManager sharaManager]

@interface FindViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,MHDataHelperDelegate>
//tableview 最热 最新 关注
@property (weak, nonatomic) IBOutlet UITableView *hotTV;
@property (weak, nonatomic) IBOutlet UITableView *recentlyTV;
@property (weak, nonatomic) IBOutlet UITableView *attentionTV;
//数组 最热 最新 关注
@property (nonatomic,strong)NSMutableArray *hotArray;
@property (nonatomic,strong)NSMutableArray *recentlyArray;
@property (nonatomic,strong)NSMutableArray *attentionArray;

//控件
@property (nonatomic,strong)UISegmentedControl *messageControl;
@property (weak, nonatomic) IBOutlet UIScrollView *scroV;
@property (nonatomic,strong)UIImageView *backgroundView;
@end

@implementation FindViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    [self addviews];
//    最热 数据请求？？？？？？？？？
    [HELPER requestHotArraydidFinish:^(FindModel *temp) {
        [self.hotArray addObject:temp];
        [self.hotArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            FindModel *find1 = obj1;
            FindModel *find2 = obj2;
            return find1.replys > find2.replys;
        }];
        [self.hotTV reloadData];
    }];
}
-(void)viewWillAppear:(BOOL)animated{
//    view将要出现 tabbar出现
    [self.tabBarController.tabBar setHidden:NO];
//    异步请求数据 请求完了自动刷新 不影响显示速度，卡顿
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        //    请求数据，并刷新tableview
        [HELPER requestRecentlyArraydidFinish:^(NSMutableArray *array) {
            self.recentlyArray = array;
            [self.recentlyTV reloadData];
        }];
    });
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [HELPER requestAllMyAttentionTopicdidFinished:^(NSMutableArray *array) {
            self.attentionArray = array;
            [self.attentionTV reloadData];
        }];
    });
}
//===？？？===
-(void)hotTVreload{
    [self.hotTV reloadData];
}
//=====================一般不改============================================
//cell 设置ok===
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    FindTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FindListCell"];
    
    [cell.imageBtn setImage:[UIImage imageNamed:@"bofang22"] forState:(UIControlStateNormal)];
    cell.imageBtn.tintColor = [UIColor whiteColor];
    
    //    最热 最新 关注
    if ([tableView isEqual:self.hotTV]) {
        FindModel *find = nil;
        if (self.hotArray.count) {
            find = self.hotArray[_hotArray.count-1-indexPath.row];
        }
        cell.timeLabel.text = [NSString stringWithFormat:@"%ld回复",find.replys];
        cell.messageLabel.text = find.topicMessage;
        cell.nameLabel.text = find.owner[@"nickname"];
        [cell.imageBtn setBackgroundImage:[UIImage imageNamed:find.owner[@"userImageName"]] forState:(UIControlStateNormal)];
    }else if ([tableView isEqual:self.recentlyTV]){
        FindModel *find = nil;
        if(self.recentlyArray.count)
        {
            find = self.recentlyArray[_recentlyArray.count-1-indexPath.row];
        }
        cell.timeLabel.text = find.startTime;
        cell.messageLabel.text = find.topicMessage;
        cell.nameLabel.text = find.owner[@"nickname"];
        [cell.imageBtn setBackgroundImage:[UIImage imageNamed:[find.owner valueForKey:@"userImageName"]] forState:(UIControlStateNormal)];
    }else{
        FindModel *find = nil;
        if (self.attentionArray.count) {
            find   = self.attentionArray[_attentionArray.count-1-indexPath.row];
        }
        cell.timeLabel.text = find.startTime;
        cell.messageLabel.text = find.topicMessage;
        cell.nameLabel.text = find.owner[@"nickname"];
        [cell.imageBtn setBackgroundImage:[UIImage imageNamed:[find.owner valueForKey:@"userImageName"]] forState:(UIControlStateNormal)];
    }
    cell.timeLabel.textAlignment = NSTextAlignmentCenter;
    cell.imageBtn.layer.masksToBounds = YES;
    cell.imageBtn.layer.cornerRadius =  cell.imageBtn.frame.size.width/2.0;
    cell.imageBtn.tag = indexPath.row +101;
    [cell.imageBtn addTarget:self action:@selector(listenVoice:) forControlEvents:(UIControlEventTouchUpInside)];
    
    cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
    cell.selectedBackgroundView.backgroundColor = [UIColor whiteColor];
    cell.messageLabel.numberOfLines = 0;
    
    cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
    cell.selectedBackgroundView.backgroundColor = [UIColor clearColor];
    return cell;
}
//cell 点击事件ok===
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ReplyViewController *replyVC = [ReplyViewController new];
    //    最热 最新 关注
    if (self.messageControl.selectedSegmentIndex == 0) {
        replyVC.findModel = self.hotArray[_hotArray.count-1-indexPath.row];
        
    }else if (self.messageControl.selectedSegmentIndex == 1){
        replyVC.findModel = self.recentlyArray[_recentlyArray.count-1-indexPath.row];
    }else{
        replyVC.findModel = self.attentionArray[_attentionArray.count-1-indexPath.row];
    }
    replyVC.ControlType = @"topic";
    HELPER.pushIndex += 1;
   
    replyVC.BarType = @"findType";
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:replyVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    
}

//播放语音ok===
-(void)listenVoice:(UIButton *)sender{
    
    if (self.messageControl.selectedSegmentIndex == 0) {
        FindModel *find = self.hotArray[_hotArray.count-sender.tag+100];
        [PLAY playRecordSuccessWithURL:find.messageVoice];
    }else if (self.messageControl.selectedSegmentIndex == 1){
        FindModel *find = self.recentlyArray[_recentlyArray.count-sender.tag+100];
        NSLog(@"%ld",_recentlyArray.count-sender.tag+100);
        [PLAY playRecordSuccessWithURL:find.messageVoice];
    }else if (self.messageControl.selectedSegmentIndex == 2){
        FindModel *find = self.attentionArray[_attentionArray.count-sender.tag+100];
        [PLAY playRecordSuccessWithURL:find.messageVoice];
    }
    
}
//下拉刷新ok===
-(void)hotRefresh{
    RealReachability *reachability = [RealReachability sharedInstance];
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    
    NSLog(@"当前网络状态%ld",status);
    
    if (status == RealStatusNotReachable) {
        
        UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            
            
        }];
        
        UIAlertController *con = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前无网络连接" preferredStyle:(UIAlertControllerStyleAlert)];
        
        [con addAction:act];
        [self presentViewController:con animated:YES completion:nil];
        
        
    }else{//网络判断
    
    if (self.hotArray.count) {
        [self.hotArray removeAllObjects];
    }
    [HELPER requestHotArraydidFinish:^(FindModel *temp) {
        [self.hotArray addObject:temp];
        [self.hotArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            FindModel *find1 = obj1;
            FindModel *find2 = obj2;
            return find1.replys > find2.replys;
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"-----%ld",self.hotArray.count);
            [self.hotTV reloadData];
            [self.hotTV.mj_header endRefreshing];
        });
    }];
    }//网络判断
}
-(void)recentlyRefresh{
    RealReachability *reachability = [RealReachability sharedInstance];
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    
    NSLog(@"当前网络状态%ld",status);
    
    if (status == RealStatusNotReachable) {
        
        UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            
            
        }];
        
        UIAlertController *con = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前无网络连接" preferredStyle:(UIAlertControllerStyleAlert)];
        
        [con addAction:act];
        [self presentViewController:con animated:YES completion:nil];
        
        
    }else{//网络判断
    
    [HELPER requestRecentlyArraydidFinish:^(NSMutableArray *array) {
        if(self.recentlyArray.count)
        {
            [self.recentlyArray removeAllObjects];
        }
        self.recentlyArray = array;
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"-----%ld",self.recentlyArray.count);
            [self.recentlyTV reloadData];
            [self.recentlyTV.mj_header endRefreshing];
        });
    }];
    }//网络判断
}
-(void)attentionRefresh{
    RealReachability *reachability = [RealReachability sharedInstance];
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    
    NSLog(@"当前网络状态%ld",status);
    
    if (status == RealStatusNotReachable) {
        
        UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            
            
        }];
        
        UIAlertController *con = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前无网络连接" preferredStyle:(UIAlertControllerStyleAlert)];
        
        [con addAction:act];
        [self presentViewController:con animated:YES completion:nil];
        
        
    }else{//网络判断
    
    [HELPER requestAllMyAttentionTopicdidFinished:^(NSMutableArray *array) {
        if(self.attentionArray.count)
        {
            [self.attentionArray removeAllObjects];
        }
        self.attentionArray = array;
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"-----%ld",self.attentionArray.count);
            [self.attentionTV reloadData];
            [self.attentionTV.mj_header endRefreshing];
        });
    }];
    }//网络判断
}
//添加视图ok===
-(void)addviews{
    //    添加下拉刷新
    self.hotTV.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(hotRefresh)];
    self.recentlyTV.mj_header =  [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(recentlyRefresh)];
    self.attentionTV.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(attentionRefresh)];
    //加背景图片
    self.backgroundView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    self.backgroundView.image = [UIImage imageNamed:@"find2.jpg"];
    [self.view addSubview:self.backgroundView];
    //创建需要的毛玻璃特效类型
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    //  毛玻璃view 视图
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    //添加到要有毛玻璃特效的控件中
    effectView.frame = self.backgroundView.bounds;
    //设置模糊透明度（范围0到1）
    effectView.alpha = 0.7f;
    [self.view addSubview:effectView];
    [self.view sendSubviewToBack:effectView];
    [self.view sendSubviewToBack:self.backgroundView];
    
    //加载 初始设置
    self.title = @"发现";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.messageControl = [[UISegmentedControl alloc]initWithItems:@[@"最热",@"最新",@"关注"]];
    self.navigationItem.titleView = self.messageControl;
    self.scroV.pagingEnabled = YES;
    self.scroV.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width*3, [UIScreen mainScreen].bounds.size.height);
    //分段控件 添加事件
    [self.messageControl addTarget:self action:@selector(changeAction:) forControlEvents:(UIControlEventValueChanged)];
    //设置格式
    self.messageControl.sd_layout
    .heightIs(30)
    .widthIs([UIScreen mainScreen].bounds.size.width*0.5);
    //    注册cell 最热 最新 关注
    UINib *nib = [UINib nibWithNibName:@"FindTableViewCell" bundle:nil];
    [self.hotTV registerNib:nib forCellReuseIdentifier:@"FindListCell"];
    [self.recentlyTV registerNib:nib forCellReuseIdentifier:@"FindListCell"];
    [self.attentionTV registerNib:nib forCellReuseIdentifier:@"FindListCell"];
    //    设置代理
    [self addDelegate];
    
    self.messageControl.selectedSegmentIndex = 1;
    self.scroV.contentOffset = CGPointMake([UIScreen mainScreen].bounds.size.width, 0);
}
//设置代理ok===
-(void)addDelegate{
    self.hotTV.delegate = self;
    self.hotTV.dataSource = self;
    self.recentlyTV.delegate = self;
    self.recentlyTV.dataSource = self;
    self.attentionTV.delegate = self;
    self.attentionTV.dataSource = self;
    self.scroV.delegate = self;
    [MHDataHelper shareDataHelper].hotTVReloadDelegate = self;
}
//滑动 分段控件跟着变ok===
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    self.messageControl.selectedSegmentIndex = self.scroV.contentOffset.x/[UIScreen mainScreen].bounds.size.width;
    NSString *imageName = [NSString stringWithFormat:@"find%ld.jpg",self.messageControl.selectedSegmentIndex+1];
    self.backgroundView.image = [UIImage imageNamed:imageName];
}
//分段控件 点击事件ok===
-(void)changeAction:(UISegmentedControl *)sender{
    [self.scroV setContentOffset:CGPointMake([UIScreen mainScreen].bounds.size.width*sender.selectedSegmentIndex, 0) animated:YES];
    NSString *imageName = [NSString stringWithFormat:@"find%ld.jpg",sender.selectedSegmentIndex+1];
    self.backgroundView.image = [UIImage imageNamed:imageName];
}
//最热 最新 关注 －－行数ok===
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:self.hotTV]) {
        return self.hotArray.count;
    }else if ([tableView isEqual:self.recentlyTV]){
        return self.recentlyArray.count;
    }else
        return self.attentionArray.count;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}
//懒加载
-(NSMutableArray *)hotArray{
    if (!_hotArray) {
        _hotArray = [NSMutableArray array];
    }
    return _hotArray;
}
-(NSMutableArray *)recentlyArray{
    if (!_recentlyArray) {
        _recentlyArray = [NSMutableArray array];
    }
    return _recentlyArray;
}
-(NSMutableArray *)attentionArray{
    if (!_attentionArray) {
        _attentionArray = [NSMutableArray array];
    }
    return _attentionArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
